<template>
    <el-card shadow="hover" :body-style="{ padding: '20px' }">
        <!-- 添加品牌的按钮 -->
        <el-button type="primary" size="default" :icon="Plus" @click="dialogFormVisible=true">添加</el-button>
        <!-- 展示商品数据的表格 -->
        <el-table border style="margin: 20px 0px;" :data="tmObj.records" v-loading="loading"
            element-loading-text="努力加载中...">
            <el-table-column label="序号" align="center" width="80" type="index"></el-table-column>
            <el-table-column label="品牌名称" align="center" prop="tmName"></el-table-column>
            <el-table-column label="品牌LOGO" align="center">
                <template #="{ row, $index }">
                    <a title="row.tmName">
                        <img :src="row.logoUrl" style="width:100px;height:80px;">
                    </a>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template #="{ row, $index }">
                    <el-button type="warning" size="small" :icon="Edit" @click="updateTradeMark(row)">
                    </el-button>
                    <el-popconfirm :title="`你确定删除${row.tmName}?`" width="250px" :icon="Delete" @confirm="handler(row)">
                        <template #reference>
                            <el-button type="danger" size="small" :icon="Delete"></el-button>
                        </template>
                    </el-popconfirm>

                </template>
            </el-table-column>
        </el-table>

        <!-- 分页器
            current-page:当前页码  
            page-sizes：每页展示条数
            page-sizes：每页展示条数更改
            layout：布局
            pager-count：能看见的按钮总个数
           -->
        <el-pagination v-model:current-page="currentPage" @current-change="getTradeMarkList"
            v-model:page-size="pageSize" @size-change="sizeHandler" :page-sizes="[3,5,7]"
            layout="prev, pager, next, jumper,->,sizes,total" :total="tmObj.total" background :pager-count="7">
        </el-pagination>

        <!-- 添加弹窗 -->
        <el-dialog v-model="dialogFormVisible" :title="tmParams.id?'修改品牌':'添加品牌'" draggable @click="addTradeMark()">
            <el-form style="width:80%; margin-left:20px" label-width="90px" :model="tmParams" :rules="rules"
                ref="formRef">
                <!-- 品牌名称 -->
                <el-form-item label="品牌名称" prop="tmName">
                    <el-input autocomplete="off" v-model="tmParams.tmName" />
                </el-form-item>
                <!-- 品牌LOGO -->
                <el-form-item label="品牌LOGO" prop="logoUrl">
                    <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="tmParams.logoUrl" :src="tmParams.logoUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <!-- 弹窗底部 -->
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="addOrUpdate">确认</el-button>
                </span>
            </template>
        </el-dialog>

    </el-card>
</template>

<script setup lang="ts">
//引入图标
import { Plus, Delete, Edit } from "@element-plus/icons-vue";
import { ref, onMounted, reactive,nextTick } from 'vue'
import { reqTradeMarkList, reqAddOrUpdateTradeMark, reqDeleteTradeMark } from '@/api/product/trademark/trademark'
// 数据类型
import type { trademarkResponseData, trademark } from '@/api/product/trademark/model/trademark'
// element自带样式类型
import type { UploadProps, FormInstance, FormRules } from "element-plus";
//消息提示框
import { ElMessage, ElNotification } from "element-plus";


let currentPage = ref<number>(1)
let pageSize = ref<number>(3)
//定义接受服务器返回的品牌数据:total|records
let tmObj = reactive<trademarkResponseData>({
    total: 0,
    records: []
});
//定义控制loding效果响应式数据
let loading = ref<boolean>(false)
//控制dialog对话框显示与隐藏
let dialogFormVisible = ref<boolean>(false);
//存储组件实例el-form
let formRef = ref<FormInstance>();
//组件挂载完毕先发送请求
onMounted(() => {
    getTradeMarkList()
});
//收集新增品牌数据-将来发请求携带给服务器
let tmParams = reactive<trademark>({
    tmName: "",
    logoUrl: "",
});

//获取品牌信息
const getTradeMarkList = async (page: number = 1) => {
    //发请求之前loading加载
    loading.value = true;
    //参数整理一下
    currentPage.value = page;
    let result = await reqTradeMarkList(currentPage.value, pageSize.value);
    tmObj.total = result.total;
    tmObj.records = result.records;
    //服务器数据回来loading效果取消
    loading.value = false;
}

//右边下拉菜单修改一页展示几条数据的回调
const sizeHandler = (limit: number) => {
    //整理参数
    pageSize.value = limit;
    //再次发请求
    getTradeMarkList();
}

//添加图片成功的钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    tmParams.logoUrl = response.data;
}

//上传前的钩子
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    //约束类型
    if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/gif' || rawFile.type == 'image/png') {
        //约束大小
        if (rawFile.size / 1024 / 1024 <= 5) {
            return true
        }
    } else {
        return false
    }

}

//确定按钮的回调
const addOrUpdate = async () => {
    formRef.value?.validate(async (success) => {
        if (success) {
            //发送请求
            await reqAddOrUpdateTradeMark(tmParams);
            //关闭弹窗
            dialogFormVisible.value = false;
            //再次获取品牌信息
            getTradeMarkList(tmParams.id ? currentPage.value : 1);
            ElMessage({
                message: tmParams.id ? '修改品牌成功' : '添加标题成功',
                type: "success",
            });
        } else {
            ElNotification({
                type: "warning",
                message: "大哥你看点规则,别瞎搞",
                duration: 1000//提示消息时间的设置
            });
        }
    })
};

//添加品牌的回调
const addTradeMark = () => {
    //对话框显示出来
    dialogFormVisible.value = true;
    //每一次对话框显示出来的时候，清空数据[把上一次收集的数据不要了，从新收集]
    tmParams.tmName = '';
    tmParams.logoUrl = '';
    tmParams.id = '';
    //nextTick:当响应式数据发生变化[页面重新渲染],获取更新后的DOM
    nextTick(() => {
        formRef.value.resetFields();
    });
}

//修改功能实现
const updateTradeMark = (row: trademark) => {
    //对话框显示出来
    dialogFormVisible.value = true;
    tmParams.tmName = row.tmName;
    tmParams.logoUrl = row.logoUrl;
    tmParams.id = row.id;
}

//自定义校验规则
const validatetmName = (rule:any,value:any,next:any)=>{
    if(value.length >= 2){
        next();
    }else{
        next(new Error('品牌名字数应大于等于2'))
    }
}

//表单验证规则
const rules = reactive<FormRules>({
    tmName: [
        // 自定义校验规则validator,自定义校验规则
        { required: true, trigger: "blur", validator: validatetmName },
    ],
    logoUrl: [{ required: true, message: "请你上传logo图片" }],
});

//删除功能
const handler = async (row: trademark) => {
    try {
        //删除品牌成功
        await reqDeleteTradeMark(row.id);
        //提示信息
        ElMessage({
            type: "success",
            message: `删除${row.tmName}成功`,
        });
        //再次获取最新数据
        getTradeMarkList(currentPage.value);
    } catch (error) { }
}

</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
    
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>